from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.pagelayout import PageLayout
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image as kiImage
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import os

IMG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'white.png')
print(IMG_PATH)
LOAD_IMAGE = u'选择加载图片'
SAVE_IMAGE = u'保存图片'
INFO = u'请加载图片、框住区域（待开发）、保存（待开发）……'
FONT = 'uming.ttc'  # LINUX
# FONT = 'simhei'  # WINDOWS

Builder.load_string(f'''
<MainLayout>
    id: sm
    
    Screen
        canvas.before:
            Color:
                rgb: .2, .2, .2
            Rectangle:
                size: self.size
        name: 'main_page'
        BoxLayout
            orientation:'vertical'
            pos_hint: {{'top': 1}}  # https://stackoverflow.com/questions/34470366/keep-widget-on-top-in-kivy
            spacing:5
            padding:5
            BoxLayout
                orientation:'horizontal'
                size_hint_y: None
                height: '48dp'
                spacing:5
                padding:5
                Button:
                    id:btn_load
                    text:'{LOAD_IMAGE}'
                    on_press: app.on_btn_press(self.text)
                    font_name: '{FONT}'
                Button:
                    id:btn_save
                    text:'{SAVE_IMAGE}'
                    on_press: app.on_btn_press(self.text)
                    font_name: '{FONT}'
            Label:
                id:label
                height: '48dp'
                size_hint_y: None
                text: '{INFO}'
                text_size: self.width, None
                font_name: '{FONT}'
                halign: 'center'
                valign: 'middle'  # 'bottom', 'middle', 'center', 'top'
            Image:
                id:image
                source: r'{IMG_PATH}'
                size_hint: 1, 1
                fit_mode: 'fill'
                
    Screen:
        canvas.before:
            Color:
                rgb: .2, .8, .2
            Rectangle:
                size: self.size
        name: 'chooser_page'        
        BoxLayout:
            id: chooser_page
            orientation: 'vertical'
        
            BoxLayout:
                size_hint_y: None
                height: sp(52)
        
                Button:
                    text: '图标'
                    on_press: fc.view_mode = 'icon'
                    font_name: '{FONT}'
                Button:
                    text: '列表'
                    on_press: fc.view_mode = 'list'
                    font_name: '{FONT}'
        
            FileChooser:
                id: fc
                on_submit: sm.current = 'main_page'
                # on_submit: app.on_select_image(self.selection[0], image.size)  # https://stackoverflow.com/questions/38520218/kivy-language-multiple-commands-in-a-single-line
                on_submit: image.source = self.selection[0]
                FileChooserIconLayout
                FileChooserListLayout
''')


class MainLayout(ScreenManager):

    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)


class ButtonsApp(App):
    def build(self):
        self.root = MainLayout()
        self.root.current = 'main_page'  # https://stackoverflow.com/questions/56225748/set-default-screen-based-on-return-value-in-kivy
        return self.root

    def on_btn_press(self, text):
        if LOAD_IMAGE == text:
            self.root.current = 'chooser_page'
        elif SAVE_IMAGE == text:
            self.root.ids.label.text = u'成功保存图片！'
        else:
            print('Something wrong ...')

    # def on_select_image(self, img_path, size):
    #     """
    #     https://stackoverflow.com/questions/51806100/display-pil-image-on-kivy-canvas
    #     :param path:
    #     :return:
    #     """
    #     print(img_path, size)
    #     canvas_img = Image.open(img_path)
    #     # https://stackoverflow.com/questions/6444548/how-do-i-get-the-picture-size-with-pil
    #     width, height = canvas_img.size
    #
    #     # https://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio
    #     ratio = min(size[0]/width, size[1]/height)
    #     width, height = width * ratio, height * ratio
    #     width = int(width)
    #     height = int(height)
    #     canvas_img = canvas_img.resize((width, height), Image.LANCZOS)  # https://stackoverflow.com/questions/76616042/attributeerror-module-pil-image-has-no-attribute-antialias
    #
    #     data = BytesIO()
    #     canvas_img.save(data, format='png')
    #     data.seek(0)  # yes you actually need this
    #     im = CoreImage(BytesIO(data.read()), ext='png')
    #     self.root.ids.image = kiImage()  # only use this line in first code instance
    #     self.root.ids.image.texture = im.texture


if __name__ == '__main__':

    ButtonsApp().run()
